<template>
    <view class="productlist">
        <view class="pindetail">
            <view class="banner">
                <swiper
                    @change="changeEvent"
                    class="swiperimg"
                    indicator-dots="true"
                    interval="5000"
                    duration="1000"
                    current="dots_icon"
                    indicator-color="rgba(255,255,255,.3)"
                    indicator-active-color="#fff"
                >
                    <block v-for="(item, index) in goodDetail.picList" :key="index">
                        <swiper-item :style="{ backgroundImage: 'url(' + item + ')' }"></swiper-item>
                    </block>
                </swiper>
                <text class="item-num"
                    >{{ topSwiperIndex + 1 }}
                    <text style="color: #fff; font-size: 24rpx">/{{ goodDetail.picList.length }}</text></text
                >
            </view>
            <view class="youh">
                <view class="youh-top">
                    <view class="title-p1">
                        <view>
                            <text style="font-size: 28rpx">￥</text><text>{{ goodDetail.goodsMinPrice }}</text>
                        </view>
                    </view>
                    <view class="youh-num">已售{{ goodDetail.actualSales || "" }}件</view>
                </view>
                <view class="youh-title">{{ goodDetail.name }}</view>
            </view>
            <view v-if="couponList.length > 0" style="height: 20rpx; width: 100%; background-color: #f6f6f6"></view>
            <view class="couponArea" v-if="couponList.length > 0" @click="chooseCoupon">
                <view>领券</view>
                <view class="couponList">
                    <view class="couponItem" v-for="(item, index) in couponList.slice(0, 2)" :key="index">
                        {{ getCouponText(item) }}
                    </view>
                </view>
                <image mode="widthFix" src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/mall/coupon.png" class="couponIcon"></image>
            </view>
            <view style="height: 20rpx; width: 100%; background-color: #f6f6f6"></view>
            <view class="intro">
                <rich-text style="margin: 0 0 30rpx" space="nbsp" :nodes="goodsRichText"></rich-text>
            </view>
        </view>

        <view style="height: 200rpx"></view>
        <view class="DetailBottom" :style="{ paddingBottom: isIphoneX ? 'env(safe-area-inset-bottom)' : '20rpx' }">
            <view style="position: relative" class="li">
                <image mode="widthFix" src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/homemenu/share1.png"></image>
                <view class="p">分享</view>
                <button class="wxBtn" open-type="share"></button>
            </view>
            <view class="right" @click="buyEvent()">立即购买</view>
        </view>
        <product-sku @goNext="goNext" :show="show" @close="close" :goodsData="goodDetail"></product-sku>
        <CouponPop :show="couponShow" @close="couponClose" :couponList="couponList" @couponClick="receiveCoupon" />
    </view>
</template>

<script>
import request from "@/common/api/request.js";
import { mapState, mapMutations } from "vuex";
import utils from "../../common/utils";
import CouponPop from "@/components/couponPop/index.vue";
export default {
    components: {
        CouponPop,
    },
    data() {
        return {
            request,
            topSwiperIndex: 0,
            id: "",
            show: false,
            isIphoneX: false,
            goodDetail: {
				picList: [],
				specsDataList: [],
			},
            couponList: [],
            couponShow: false,
        };
    },
    onLoad(options) {
        this.id = options.id;
        utils.checkIphoneX().then((res) => (this.isIphoneX = res));
        this.request.httpTokenJsonRequest(`/mp-api/wx/goods/details/${this.id}`, null, "POST", false).then((res) => {
            if (res.code == 0) {
                this.goodDetail = res.data;
                this.goodDetail.details = this.goodDetail.details.replace(
                    /<img/g,
                    "<img style='max-width:100%;height:auto;'",
                );
                this.getEnableCoupon();
            }
        });
    },
    computed: {
        ...mapState(["isLogin", "userInfo"]),
        goodsRichText() {
            let text = this.goodDetail.details || "";
            return text.replaceAll(
                `<img style='max-width:100%;height:auto;' src="/dev-api`,
                `<img style='max-width:100%;height:auto;' src="${this.request.baseUrl}`,
            );
        },
    },
    methods: {
        ...mapMutations(["loginSaveUserInfo", "logout"]),
        async getEnableCoupon() {
            const { data } = await this.request.httpTokenJsonRequest(
                "/mp-api/wx/coupon/receiveGoodsCoupon",
                {
                    goodsNoList: [this.goodDetail.goodsId],
                },
                "POST",
                true,
            );
            this.couponList = data || [];
        },
        /** 领取优惠券 */
        async receiveCoupon(data) {
            try {
                await this.request.httpTokenJsonRequest(
                    "/mp-api/wx/coupon/receive",
                    {
                        templateNo: data.templateNo,
                        acceptType: 0, // 领取渠道 0.手动领取(注：普通券，商品详情处领取) 2.新人奖励
                    },
                    "GET",
                    true,
                );
                uni.showToast({
                    title: "领取成功",
                    icon: "success",
                });
            } catch (e) {
                //TODO handle the exception
                uni.showToast({
                    title: e.msg,
                    icon: "none",
                });
            }
            this.getEnableCoupon();
        },
        getSystem() {
            uni.getSystemInfo({
                success(res) {
                    let name = "iphone x";
                    let iname = "iphone 1";
                    const deviceName = res.model.toLocaleLowerCase();
                    if (deviceName.includes(name) || deviceName.includes(iname)) {
                        resolve(true);
                    } else {
                        resolve(false);
                    }
                },
            });
        },
        buyEvent() {
            if (this.isAuthNicknamePhone() == false) {
                return;
            }
            this.show = true;
        },
        requestUser() {
            this.request
                .httpTokenRequest(`/mp-api/wx/user/detail/${this.userInfo.uid}`, null, "POST", true)
                .then((res) => {
                    if (res.code == 0) {
                        this.loginSaveUserInfo(res.data);
                    }
                });
        },
        isAuthNicknamePhone() {
            if (this.userInfo.nickname == "" || this.userInfo.nickname == null || this.userInfo.nickname == undefined) {
                this.authUserInfo();
                return false;
            }
            if (this.userInfo.phone == "" || this.userInfo.phone == null || this.userInfo.phone == undefined) {
                uni.navigateTo({
                    url: "/pages/login/login",
                });
                return false;
            }
            return true;
        },
        authUserInfo() {
            uni.getUserProfile({
                desc: "Wexin",
                success: (res) => {
                    let avatar = res.userInfo.avatarUrl;
                    let nickname = res.userInfo.nickName;
                    this.sendUserInfo(avatar, nickname);
                },
            });
        },
        sendUserInfo(avatar, nickname) {
            var postData = {};
            postData.uid = this.userInfo.uid;
            postData.avatar = avatar;
            postData.nickname = nickname;
            this.request.httpTokenJsonRequest("/mp-api/wx/user/update", postData, "POST", false).then((res) => {
                if (res.code == 0) {
                    if (res.data.phone == "" || res.data.phone == null || res.data.phone == undefined) {
                        uni.navigateTo({
                            url: "/pages/login/login",
                        });
                    }
                    this.requestUser();
                }
            });
        },
        changeEvent(e) {
            this.topSwiperIndex = e.detail.current;
        },
        close() {
            this.show = false;
        },
        async goNext(orderData) {
            this.show = false;
            await this.checkGoods(orderData);
            var orderProduct = encodeURIComponent(JSON.stringify(orderData));
            this.helper.navigateTo("/packageMall/pages/order/order?orderProduct=" + orderProduct);
        },
        checkGoods(order) {
            return new Promise((resolve) => {
                this.request.httpTokenJsonRequest("/mp-api/wx/order/pre", order, "POST", false).then((res) => {
                    if (res.code == 0) {
                        resolve();
                    } else {
                        reject();
                    }
                });
            });
        },
        onShareAppMessage(res) {
            return {
                title: this.goodDetail.name,
                path: "/pages/mall/productDetail?id=" + this.id,
                imageUrl: this.request.baseUrl + this.goodDetail.cover,
                success(res) {
                    uni.showToast({
                        title: "分享成功",
                        icon: "none",
                    });
                },
                fail(res) {
                    uni.showToast({
                        title: "分享失败",
                        icon: "none",
                    });
                },
            };
        },
        onShareTimeline(res) {
            return {
                title: this.goodDetail.name,
                path: "/pages/mall/productDetail?id=" + this.id,
                imageUrl: this.request.baseUrl + this.goodDetail.cover,
                success(res) {
                    uni.showToast({
                        title: "分享成功",
                        icon: "none",
                    });
                },
                fail(res) {
                    uni.showToast({
                        title: "分享失败",
                        icon: "none",
                    });
                },
            };
        },
        getCouponText(data) {
            let reducedPrice = "";
            let thresholdAmount = "";

            if (data.useCondition != 0) {
                thresholdAmount = `满￥${data.demandPrice}`;
                if (data.couponType === 0) {
                    reducedPrice = `减￥${data.price}`;
                } else {
                    reducedPrice = `享${data.discount}折`;
                }
            } else {
                if (data.couponType === 0) {
                    reducedPrice = `${data.price}元抵扣券`;
                } else {
                    reducedPrice = `${data.discount}折抵扣券`;
                }
            }
            return `${thresholdAmount}${reducedPrice}`;
        },
        couponClose() {
            this.couponShow = false;
        },
        chooseCoupon() {
            if (this.isAuthNicknamePhone() == false) {
                return;
            }
            this.couponShow = true;
        },
    },
};
</script>
<style lang="scss" scoped>
.wxBtn {
    background-color: transparent;
    width: 100%;
    height: 100%;
    flex: 1;
    top: 0;
    left: 0;
    position: absolute;
    z-index: 200;
}

button::after {
    border: none;
}

.couponArea {
    display: flex;
    align-items: center;
    padding: 22rpx 30rpx;
    background-color: #fff;
    height: 40rpx;
    font-size: 28rpx;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #333333;
    line-height: 40rpx;

    .couponList {
        flex: 1;
        overflow-x: auto;
        display: flex;
        align-items: center;
    }

    .couponItem {
        height: 44rpx;
        background: rgba(255, 65, 59, 0.06);
        margin-left: 20rpx;
        padding: 0 16rpx;
        border-radius: 2rpx;
        font-size: 24rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        color: #ff413b;
        line-height: 44rpx;
    }

    .couponIcon {
        width: 32rpx;
        height: 32rpx;
    }
}
</style>
